package com.datastructure.test.groupanagrams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class GroupAnagrams {

    public static void main(String[] args) {
        GroupAnagrams groupAnagrams = new GroupAnagrams();
        String[] strs = {"eat", "tea", "ate", "but","nowcoder","codernow"};
        String[][] anagrams = groupAnagrams.groupAnagrams(strs);
        System.out.println(anagrams);
    }

    public String[][] groupAnagrams (String[] strs) {
        // write code here
        String[] temp = new String[strs.length];
        HashMap<String, ArrayList<Integer>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            handleString(i,strs[i],temp);
        }
        String s ;
        ArrayList<Integer> list;
        int length = 0;
        for (int i = 0; i < temp.length; i++) {
            s = temp[i];
            if (map.containsKey(s)) {
                list=map.get(s);
                list.add(i);
                length=Math.max(length,list.size());
            } else {
                list = new ArrayList<>();
                list.add(i);
                length=Math.max(length,list.size());
                map.put(s,list);
            }
        }
        String[][] result = new String[map.size()][];
        String[] strings = map.keySet().toArray(new String[0]);
        for (int i = 0; i < strings.length; i++) {
            list=map.get(strings[i]);
            result[i]=new String[list.size()];
            for (int j = 0; j < list.size(); j++) {
                result[i][j]=strs[list.get(j)];
            }
        }
        return result;
    }

    private void handleString(int i, String str, String[] strs) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        strs[i]=new String(chars);
    }
}
